from rest_framework import serializers
from clinicalGuidelines.models import ClinicalDepartmentModel, ClinicalGuidelinesModel, ClinicalGuidelineContentModel

# 临床科室序列化器
class ClinicalDepartmentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ClinicalDepartmentModel
        fields = ['name']

# 临床指南序列化器
class ClinicalGuidelinesModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ClinicalGuidelinesModel
        fields = ['title', 'clinical_department']

# 临床指南内容序列化器
class ClinicalGuidelineContentModelSerializer(serializers.ModelSerializer):
    # 嵌套序列化指南标题
    guideline = ClinicalGuidelinesModelSerializer(read_only=True)

    class Meta:
        model = ClinicalGuidelineContentModel
        fields = ['guideline', 'title', 'release_date', 'Maker', 'source', 'summary', 'clinical_guidelines', 'recomment_home']

    def create(self, validated_data):
        guideline_data = validated_data.pop('guideline')
        guideline = ClinicalGuidelinesModel.objects.create(**guideline_data)
        title = ClinicalGuidelineContentModel.objects.create(guideline=guideline, **validated_data)
        return title

    def update(self, instance, validated_data):
        guideline_data = validated_data.pop('guideline')
        instance.guideline = ClinicalGuidelinesModel.objects.update_or_create(**guideline_data)[0]
        instance.title = validated_data.get('title', instance.title)
        instance.save()
        return instance